package com.exchange.used.service.impl;

import com.exchange.used.config.converters.LayuiResult;
import com.exchange.used.config.query.Condition;
import com.exchange.used.entity.Address;
import com.exchange.used.entity.Goods;
import com.exchange.used.entity.Order;
import com.exchange.used.entity.Record;
import com.exchange.used.repository.*;
import com.exchange.used.service.OrderServiceI;
import com.exchange.used.service.RestfulServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service("OrderService")
public class OrderService implements OrderServiceI {

    @Autowired
    OrderRepository orderRepository;
    @Autowired
    RecordRepository recordRepository;
    @Autowired
    GoodsRepository goodsRepository;
    @Autowired
    AddressRepository addressRepository;
    @Autowired
    ListRepository listRepository;
    @Autowired
    RestfulServiceI restfulServiceI;

    @Override
    @Transactional
    public LayuiResult addOrder(String goodsid, Integer goodsnum, String fkaddressid) {
        LayuiResult result = new LayuiResult();
        try {
            Goods goods = goodsRepository.getGoodsByGoodsid(goodsid);
            Address address = addressRepository.getAddressByAddressid(fkaddressid);
            if(goods == null){
                result.setCode(-1);
                result.setMsg("该商品不存在");
                return result;
            }
            if(address == null){
                result.setCode(-1);
                result.setMsg("该地址不存在");
                return result;
            }
            if(goods.getFksellerid().equalsIgnoreCase(address.getFkuserid())){
                result.setCode(-1);
                result.setMsg("不能购买自己发布的商品");
                return result;
            }
            if(goods.getGoodnum() < goodsnum){
                result.setCode(-1);
                result.setMsg("购买数量超出该商品剩余总数上线");
                return result;
            }
            Order order = new Order();
            order.setFkaddressid(fkaddressid);
            order.setOrdertime(new Date());
            order.setFkstateid("1");
            order.setOrderprice(goods.getGoodsprice() * goodsnum);
            order.setFkbuyerid(address.getFkuserid());
            Order newOrder = orderRepository.save(order);

            Record record = new Record();
            record.setFkgoodsid(goodsid);
            record.setRecordnum((double)goodsnum);
            record.setRecordprice(goods.getGoodsprice() * goodsnum);
            record.setFkorderid(newOrder.getOrderid());
            recordRepository.save(record);

            goods.setGoodnum(goods.getGoodnum() - goodsnum);
            goodsRepository.save(goods);

            result.setMsg("购买成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Override
    @Transactional
    public LayuiResult batchAddOrder(Map<String, Object> map) {
        LayuiResult result = new LayuiResult();
        try {
            if(map == null || map.size() == 0){
                result.setCode(-1);
                result.setMsg("empty data");
                return result;
            }
            if(map.get("fkaddressid") == null || map.get("fkaddressid").toString().isEmpty()){
                result.setCode(-1);
                result.setMsg("请选择收货地址");
                return result;
            }
            String fkbuyerid;
            if(map.get("fkbuyerid") == null){
                result.setCode(-1);
                result.setMsg("您的用户信息为空，请重新登录");
                return result;
            }else{
                fkbuyerid = map.get("fkbuyerid").toString();
            }
            if(map.get("selectData") == null || ((List<Map<String, Object>>)map.get("selectData")).size() == 0){
                result.setCode(-1);
                result.setMsg("未选择任何商品");
                return result;
            }
            List<Map<String, Object>> lists = (List<Map<String, Object>>)map.get("selectData");

            //检查购买数量是否超出
            for(Map<String, Object> list : lists){
                double goodsnum = Double.parseDouble(list.get("goodnum").toString());
                int listnum = Integer.parseInt(list.get("listnum").toString());
                if(goodsnum < listnum){
                    result.setCode(-1);
                    result.setMsg("[" + list.get("goodsname").toString() + "] : 购买数量超出剩余总数" );
                    return result;
                }
            }
            //计算总价格、商品减少相应的购买数量
            double orderPrice = 0;
            for(Map<String, Object> list : lists){
                int listnum = Integer.parseInt(list.get("listnum").toString());
                double goodsprice = Double.parseDouble(list.get("goodsprice").toString());
                orderPrice += goodsprice * listnum;

                Goods goods = goodsRepository.getGoodsByGoodsid(list.get("goodsid").toString());
                goods.setGoodnum(goods.getGoodnum()- listnum);
                goodsRepository.save(goods);
            }
            //添加order信息
            Order order = new Order();
            order.setOrderprice(orderPrice);
            order.setFkstateid("1");
            order.setFkbuyerid(fkbuyerid);
            order.setOrdertime(new Date());
            order.setFkaddressid(map.get("fkaddressid").toString());
            order.setOrderdesc(map.get("orderdesc").toString());

            //保存订单并返回订单id
            Order newOrder = orderRepository.save(order);
            String newOrderid = newOrder.getOrderid();

            //根据list保存record
            Record record;
            for(Map<String, Object> list : lists){
                record = new Record();
                record.setFkgoodsid(list.get("fkgoodsid").toString());
                record.setFkorderid(newOrderid);
                record.setRecordnum(Double.parseDouble(list.get("listnum").toString()));
                record.setRecordprice(record.getRecordnum() * Double.parseDouble(list.get("goodsprice").toString()));
                recordRepository.save(record);
            }

            //删除list中对应数据
            for(Map<String, Object> list : lists){
                if(list.get("listid") != null){
                    String listid = list.get("listid").toString();
                    listRepository.deleteById(listid);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg(e.getMessage());
        }

        return result;
    }

    @Override
    public LayuiResult remark(Map<String, Object> record) {
        LayuiResult result = new LayuiResult();
        try {
            if(record == null || record.size() == 0){
                result.setCode(-1);
                result.setMsg("data can not be null");
                return result;
            }
            if(record.get("fkgoodsid") == null || record.get("fkgoodsid").toString().isEmpty()){
                result.setCode(-1);
                result.setMsg("goods id can not be null");
                return result;
            }
            String fkgoodsid = record.get("fkgoodsid").toString();
            restfulServiceI.executeSaveOrUpdate("record", Arrays.asList(record));
            //重新计算商品评分
            List<Record> records = recordRepository.getRecordsByFkgoodsidAndStarIsNotNull(fkgoodsid);
            double total = 0;
            for(Record r : records){
                total += r.getStar();
            }
            Goods goods = goodsRepository.getGoodsByGoodsid(fkgoodsid);
            BigDecimal newGoodsStar = new BigDecimal(total).divide(new BigDecimal(records.size()), 1, RoundingMode.HALF_UP);
            goods.setGoodsstar(newGoodsStar.toString());
            goodsRepository.save(goods);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Override
    @Transactional
    public LayuiResult findUserOrder(Condition condition) {
        LayuiResult result = new LayuiResult();
        try {
            List<Map<String, Object>> orderList = restfulServiceI.executeQuery(condition);
            List<Map<String, Object>> resultList = new ArrayList<>();
            for(Map<String, Object> orderMap : orderList){
                String orderid = orderMap.get("orderid").toString();
                List<Record> recordList = recordRepository.getRecordsByFkorderid(orderid);
                List<Map<String, Object>> goodsList = new ArrayList<>();
                for(Record record : recordList){
                    Goods goods = goodsRepository.getGoodsByGoodsid(record.getFkgoodsid());
                    Map<String, Object> goodsMap= new HashMap<>(BeanMap.create(goods));
                    goodsMap.putAll(BeanMap.create(record));
                    goodsList.add(goodsMap);
                }
                Map<String, Object> resultMap = new HashMap<>(orderMap);
                resultMap.put("goodsList", goodsList);
                resultList.add(resultMap);
            }
            result.getData().put("orderList", resultList);
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            result.setCode(-1);
        }
        return result;
    }

    @Override
    @Transactional
    public LayuiResult stateFinish(String orderid) {
        LayuiResult result = new LayuiResult();
        try {
            if(orderid == null || orderid.isEmpty()){
                result.setMsg("order id can not be null");
                result.setCode(-1);
                return result;
            }
            Order order = orderRepository.getOrderByOrderid(orderid);
            if(order == null){
                result.setMsg("该订单不存在");
                result.setCode(-1);
                return result;
            }
            if(!order.getFkstateid().equalsIgnoreCase("1")){
                result.setMsg("订单状态无法执行此操作");
                result.setCode(-1);
                return result;
            }
            order.setFinishtime(new Date());
            order.setFkstateid("2");
            orderRepository.save(order);
            result.setMsg("该订单已完成");
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            result.setCode(-1);
        }
        return result;
    }

    @Override
    @Transactional
    public LayuiResult stateCancel(String orderid) {
        LayuiResult result = new LayuiResult();
        try {
            if(orderid == null || orderid.isEmpty()){
                result.setMsg("order id can not be null");
                result.setCode(-1);
                return result;
            }
            Order order = orderRepository.getOrderByOrderid(orderid);
            if(order == null){
                result.setMsg("该订单不存在");
                result.setCode(-1);
                return result;
            }
            if(!order.getFkstateid().equalsIgnoreCase("1")){
                result.setMsg("订单状态无法执行此操作");
                result.setCode(-1);
                return result;
            }
            //回退所有商品数量
            List<Record> records = recordRepository.getRecordsByFkorderid(orderid);
            for(Record record : records){
                Goods goods = goodsRepository.getGoodsByGoodsid(record.getFkgoodsid());
                goods.setGoodnum(goods.getGoodnum() + record.getRecordnum());
                goodsRepository.save(goods);
            }
            //状态设置
            order.setFinishtime(new Date());
            order.setFkstateid("-1");
            orderRepository.save(order);
            result.setMsg("该订单已取消");
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            result.setCode(-1);
        }
        return result;
    }
}
